import { apiList } from "@/api/apiList";
import { Base64 } from 'js-base64';
function useCommon(params) {

  let commonds = []
  let commondss = []

  let commonlayers = []

  let _imageLayer = []

  let _layer = new Cesium.CustomDataSource('plotlayer')
  // let _layertmp = new Cesium.CustomDataSource('tmplayer')
  let _layers = new Cesium.CustomDataSource('plotlayers')

  let _srs = 'EPSG:4326'

  function loadTif(item, dingwei = true) {

    loadjson(item, dingwei)

    let rec = getrectangle(item)


    let params = {
      layername: 'taiwan13-1',
      tifpath: 'taiwan13-1.tif',
    }



    params.tifpath = item.imgpath
    let namearr = item.imgpath.split("/")

    const storeName1 = params.tifpath.split('/').pop()

    let storeName1arr = storeName1.split(".")

    storeName1arr.pop()

    let storeName1res = storeName1arr.join('.')

    const storeNameURL1 = Base64.encode(storeName1res)
  const storeNameURL = storeNameURL1
  // const storeNameURL = encodeURIComponent(storeNameURL1)


    params.layername = storeNameURL

    console.log(params);

    apiList.shujuguanli.genWmsService(params).then(res => {
      console.log(1111);

      // wmts
      let basemapSource = new Cesium.WebMapTileServiceImageryProvider({
        //  对与url  很多博客都说要进行 如下拼接
        // 后端返回的wmts/rest/{layer}/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png
        // 其实不用拼接  只需要后端返回的/wtms路径即可
        url: '/geoserver/gwc/service/wmts', //服务地址 服务地址只需要后端返回的 /WMTS   不需要给后面拼接任何东西，  
        layer: `test_tif:${params.layername}`, //图层名称 : "pucheng:satellite"
        style: '',
        format: 'image/png',
        tileMatrixSetID: _srs,  // "EPSG:900913"
        // 地图飞入  定位的坐标  后端返回的数据
        rectangle: rec,
        // 必须加  不然地图出不来
        //之所以要在这里提出这个tileMatrixLabels参数，是因为GeoServer在缓冲切分瓦片时对每一个缩放级别的存储目录没有使用相应的数字，而使用了网格+级别的方式来命名，如“EPSG:9100913:10”表示的是使用“EPSG:9100913”网格切分的第10级瓦片。
        tileMatrixLabels: [`${_srs}:0`, `${_srs}:1`, `${_srs}:2`, `${_srs}:3`, `${_srs}:4`, `${_srs}:5`, `${_srs}:6`,
        `${_srs}:7`, `${_srs}:8`, `${_srs}:9`, `${_srs}:10`, `${_srs}:11`, `${_srs}:12`, `${_srs}:13`, `${_srs}:14`,
        `${_srs}:15`, `${_srs}:16`, `${_srs}:17`, `${_srs}:18`, `${_srs}:19`, `${_srs}:20`, `${_srs}:21`,
        ],
        // 必须加  不然地图出不来
        tilingScheme: new Cesium.GeographicTilingScheme({//此处很重要，很重要。。。
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 1
        }),
        // tilematrixset: _srs,
        // maximumLevel: 18,
      });
      let tmp_imageLayer = viewer.imageryLayers.addImageryProvider(basemapSource);

      commonlayers.push(tmp_imageLayer)

      console.log(viewer.imageryLayers);

    })

  }

  function getrectangle(item) {

    // 计算外包围盒
    let west = Number.POSITIVE_INFINITY;
    let south = Number.POSITIVE_INFINITY;
    let east = Number.NEGATIVE_INFINITY;
    let north = Number.NEGATIVE_INFINITY;


    item.item.geometry.coordinates[0].map(iitem => {
      west = Math.min(west, Cesium.Math.toRadians(iitem[0]));
      south = Math.min(south, Cesium.Math.toRadians(iitem[1]));
      east = Math.max(east, Cesium.Math.toRadians(iitem[0]));
      north = Math.max(north, Cesium.Math.toRadians(iitem[1]));
    })

    const rectangle = new Cesium.Rectangle(west, south, east, north);

    return rectangle

  }

  function loadjson(params, dingwei) {
    // loadjson

    Cesium.GeoJsonDataSource.load(params.item, {
      stroke: Cesium.Color.fromCssColorString("#00ffff"),
      fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.0),
      strokeWidth: 3,
    }).then((res) => {
      viewer.dataSources.add(res);
      if (dingwei) {

        let h = 50000

        if (params.resolution < 10) {
          h = 50000
        }else if(params.resolution >=  19.79 && params.resolution <=  100){
          h = 500000
        }else{
          
          h = 5000000
        }


        viewer.flyTo(res, {
          duration: 0.2,
          offset: new Cesium.HeadingPitchRange(0, -Cesium.Math.PI_OVER_TWO, h)
        });
      }
      commonds.push(res)
    })
  }

  function removeAll() {

    commonlayers.map(item => {
      viewer.imageryLayers.remove(item)
    })
    commonlayers = []

    commonds.map(item => {
      viewer.dataSources.remove(item);
    })
    commonds = []

    _layer.entities.removeAll()

    if (_imageLayer != '') {
      viewer.imageryLayers.remove(_imageLayer)
      _imageLayer = ''
    }

  }

  function removeAlls() {

    commondss.map(item => {
      viewer.dataSources.remove(item);
    })
    commondss = []

  }

  function getResolution(l) {

    let resolutionkv = {
      0: " resolution > 500",
      1: " resolution <=500 AND resolution > 300",
      2: " resolution <=300 AND resolution > 200",
      3: " resolution <=200 AND resolution > 100",
      4: " resolution <=100 AND resolution > 50",
      5: " resolution <=50 AND resolution > 25",
      6: " resolution <=25 AND resolution > 15",
      7: " resolution <=15 AND resolution > 10",
      8: " resolution <=10 AND resolution > 6",
      9: " resolution <=6.0",
      10: " resolution <=6.0",
      11: " resolution <=6.0",
      12: " resolution <=6.0",
      13: " resolution <=6.0",
      14: " resolution <=6.0",
      15: " resolution <=6.0",
      16: " resolution <=6.0",
      17: " resolution <=6.0",
      18: " resolution <=6.0",
      19: " resolution <=6.0",
    }

    return resolutionkv[l]


  }
  function getResolution1() {
    // 获取相机高度
    const cameraHeight = viewer.camera.positionCartographic.height;

    // 获取视场角
    const fov = viewer.camera.frustum.fov;

    // 获取屏幕宽度
    const screenWidth = viewer.scene.canvas.clientWidth;

    // 计算视域宽度
    const viewWidth = 2 * cameraHeight * Math.tan(fov / 2);

    // 计算分辨率
    const resolution = viewWidth / screenWidth;

    return resolution
  }

  function getResolutionByLevel(zoomLevel) {
    // 分辨率公式：156543.033928 / (2^zoomLevel)
    const initialResolution = 156543.033928; // Zoom 0 的分辨率
    const resolution = initialResolution / Math.pow(2, zoomLevel);
  
    return resolution;
  }

  function loadsearchrectangle(params) {
    
    return new Promise((resolve, reject) => {
      Cesium.GeoJsonDataSource.load(params, {
        stroke: Cesium.Color.fromCssColorString("#00ffff"),
        fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.0),
        strokeWidth: 3,
      }).then((res) => {
        viewer.dataSources.add(res);
        commondss.push(res)
        resolve(res)
      })
    })
  }
  function loadtmprectangle(params) {
    
    return new Promise((resolve, reject) => {
      Cesium.GeoJsonDataSource.load(params, {
        stroke: Cesium.Color.fromCssColorString("#00ffff"),
        fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.0),
        strokeWidth: 3,
      }).then((res) => {
        viewer.dataSources.add(res);
        commondss.push(res)
        resolve(res)
      })
    })
  }



  return {
    loadTif,
    getResolution,
    getResolutionByLevel,
    loadsearchrectangle,
    removeAll,
    removeAlls,
  }
}

export default useCommon